package com.cishu.orancle.common;

import lombok.Data;
import com.cishu.orancle.enums.RStatus;

import java.util.HashMap;
import java.util.Map;


/**
 * 自定义通用返回类
 */
@Data
public class R<T> {

    private Integer code; // 编码：如 1 成功，0 为失败，401 等为其他状态码

    private String msg; // 错误信息

    private T data; // 数据

    private Map<String, Object> map = new HashMap<>(); // 动态数据

    public static <T> R<T> ok(T object) {
        R<T> r = new R<>();
        r.data = object;
        r.code = RStatus.SUCCESS.getCode();
        r.msg = RStatus.SUCCESS.getMessage();
        return r;
    }

    public static <T> R<T> error() {
        return error(null);
    }

    public static <T> R<T> error(String msg) {
        R<T> r = new R<>();
        r.msg = msg == null ? RStatus.ERROR.getMessage() : msg;
        r.code = RStatus.ERROR.getCode();
        return r;
    }

    public static <T> R<T> unauthorized() {
        return unauthorized(null);
    }

    public static <T> R<T> unauthorized(String msg) {
        R<T> r = new R<>();
        r.msg = msg == null ? RStatus.UNAUTHORIZED.getMessage() : msg;
        r.code = RStatus.UNAUTHORIZED.getCode();
        return r;
    }

    public static <T> R<T> forbidden() {
        return forbidden(null);
    }

    public static <T> R<T> forbidden(String msg) {
        R<T> r = new R<>();
        r.msg = msg == null ? RStatus.FORBIDDEN.getMessage() : msg;
        r.code = RStatus.FORBIDDEN.getCode();
        return r;
    }

    public static <T> R<T> notFound() {
        return notFound(null);
    }

    public static <T> R<T> notFound(String msg) {
        R<T> r = new R<>();
        r.msg = msg == null ? RStatus.NOT_FOUND.getMessage() : msg;
        r.code = RStatus.NOT_FOUND.getCode();
        return r;
    }

    public static <T> R<T> internalServerError() {
        return internalServerError(null);
    }

    public static <T> R<T> internalServerError(String msg) {
        R<T> r = new R<>();
        r.msg = msg == null ? RStatus.INTERNAL_SERVER_ERROR.getMessage() : msg;
        r.code = RStatus.INTERNAL_SERVER_ERROR.getCode();
        return r;
    }

    public R<T> add(String key, Object value) {
        this.map.put(key, value);
        return this;
    }
}